import React, { PureComponent, Fragment, useState } from "react";
import { connect } from "dva";
import { Tree } from "antd";

const { TreeNode } = Tree;

@connect(({ loading, role }) => ({
  checkedList: role.checkedList,
  updateRoleTreeLoading: loading.effects["role/updateRoleTree"],
}))
class RoleTree extends React.Component {
  state = {
    expandedKeys: [],
    autoExpandParent: true,
    checkedKeys: this.props.checkedList || ["3"],
    selectedKeys: [],
  };

  onExpand = (expandedKeys) => {
    console.log("onExpand", expandedKeys);
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  };

  onCheck = (checkedKeys, e) => {
    const { dispatch } = this.props;
    let checkedKey = [...checkedKeys, ...e.halfCheckedKeys];
    this.setState({ checkedKeys });
    console.log(checkedKey);
    e.abc = checkedKey.join(",");
    console.log(e.abc);
    dispatch({
      type: "role/newchecked",
      payload: {
        id: e.abc,
      },
    });
  };

  onSelect = (selectedKeys, info) => {
    console.log("onSelect", info);
    this.setState({ selectedKeys });
  };

  renderTreeNodes = (data) => {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.name} key={item.menuId} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.key} {...item} />;
    });
  };

  render() {
    const { datatree } = this.props;
    console.log(datatree);
    return (
      <Tree
        checkable
        onExpand={this.onExpand}
        expandedKeys={this.state.expandedKeys}
        autoExpandParent={this.state.autoExpandParent}
        onCheck={this.onCheck}
        checkedKeys={this.state.checkedKeys}
        onSelect={this.onSelect}
        selectedKeys={this.state.selectedKeys}
      >
        {this.renderTreeNodes(datatree)}
      </Tree>
    );
  }
}

export default RoleTree;
